<template>
  <div>
    <a-popover
      v-model="visible"
      placement="bottomRight"
      trigger="click">
      <template slot="content">
        <div class="fw8 pb10" style="border-bottom:solid 1px #e6e6e6">设置表头</div>
        <div class="scroll h360 pr10">
          <draggable
            v-model="list"
            handle=".sortHandler"
            chosenClass="chosen"
            forceFallback="true"
            group="module"
            animation="1000"
            @end="onEnd">
            <transition-group>
              <div v-for="(c,i) in list" :key="`header${i}`" class="flx-b pd6">
                <div class="w140"><i class="fa fa-arrows sortHandler mr6"/>{{ c.label }}</div>
                <ZgNumber class="mr10" :width="100" v-model="c.width" @change="onHeaderChange"></ZgNumber>
                <ZgSwitch v-model="c.isShow" @change="onHeaderChange"></ZgSwitch>
              </div>
            </transition-group>
          </draggable>
          <div class="h60"></div>
        </div>
        <div class="flx-e mt10 pt10" style="border-top:solid 1px #e6e6e6">
          <ZgButton @click="loadDefault" type="link" icon="refresh" class="mr10">加载默认配置</ZgButton>
          <ZgButton @click="saveConfig" icon="check">保存配置</ZgButton>
        </div>
      </template>
      <span @click="visible=!visible" class="cpt">
        <a-tooltip title="设置表头" placement="top">
          <i class="fa fa-cog"/>
        </a-tooltip>
      </span>
    </a-popover>
  </div>
</template>
<script>
import draggable from 'vuedraggable'
export default {
  components: {
    draggable
  },
  props: {
    uniqueName: {
      type: String,
      default: ''
    },
    headers: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data () {
    return {
      visible: false,
      list: []
    }
  },
  mounted () {
    this.init()
  },
  methods: {
    init () {
      const diyHeaders = localStorage.getItem(this.currentUser.username + '_diyHeader_' + this.uniqueName)
      if (diyHeaders) {
        this.list = JSON.parse(diyHeaders)
      } else {
        this.loadDefault()
      }
    },
    loadDefault () {
      this.list = this.headers
    },
    saveConfig () {
      localStorage.setItem(this.currentUser.username + '_diyHeader_' + this.uniqueName, JSON.stringify(this.list))
      this.$success({ title: '操作成功！' })
    },
    onEnd () {
      this.list.forEach((t, i) => {
        t.sort = i + 1
      })
      this.onHeaderChange()
    },
    onHeaderChange () {
      this.$emit('change', this.list.map(t => {
        return t
      }))
    }
  }
}
</script>

<style lang="scss" scoped>
.chosen{
  border-radius:3px;
  background:#409EFF;
  color:#fff;
}
</style>
